package yxy.game.pm2.command.pay;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import yxy.apple.logger.Logger;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.module.OrderInfoModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.order.OrderInfo;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.message.PayMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.pay.PostUtil;
import yxy.game.pm2.module.stat.StatHandle;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;

/**
 * 处理客户端订单询问
 *
 * @author Dell
 */
@MessageType(proto = Command.GoodsOrder, classtype = PayMessage.GoodsOrderRequest.class)
public class CMD_GoodsOrder extends Command<PayMessage.GoodsOrderRequest> {

    private static final Logger logger = Logger.create(CMD_GoodsOrder.class);

    private static final String weixin_jh_finishorder_report = "https://pay.api.xjhgame.net/union/miniapp/order/cp-notify";

    @Override
    public void execute(MessageSource messageSource, PayMessage.GoodsOrderRequest request) throws Exception {
        String pcode = messageSource.getTag();
        String myorderid = request.getOrderid();

        PayMessage.GoodsOrderResponse.Builder response = PayMessage.GoodsOrderResponse.newBuilder();
        try {
            if (OrderInfo.lockOrderInfo(pcode)) {
                OrderInfo oi = OrderInfo.get(pcode, myorderid);
                response.setOrderid(myorderid);
                if (oi == null) {
                    send(messageSource, response, Result.PayNullOrderInfo);
                    return;
                }

                if (oi.getOrderstate() == OrderInfoModule.orderinfofinish) {
                    send(messageSource, response, Result.PayOrderInfoFinish);
                    return;
                }

                if (oi.getOrderstate() == OrderInfoModule.orderinfofail) {
                    send(messageSource, response, Result.PayOrderInfoFail);
                    return;
                }

                int fristgold = 0;
                try {
                    fristgold = ActiveModule.getFirstGold(pcode, oi.getGoodsid());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                OrderInfoModule.dealFinishOrderInfo(oi);
                StatHandle.stat_支付统计(pcode, oi);

                ArrayList<Currency> curs = oi.getCurs();
                if (curs != null && curs.size() != 0) {
                    if (fristgold != 0) {
                        Currency cur = Currency.create(CurrencyType.CT_元宝, -1, fristgold);
                        curs.add(cur);
                        curs = new ArrayList<Currency>(Currency.merge(curs));
                    }
                    new CurrencyHandle().addCurrency(pcode, CCReason.用户购买, curs);
                }

                ActiveModule.HandleActiveAddVipexp(pcode, oi);

                if (curs != null && curs.size() != 0) {
                    Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
                    response.addAllDisplay(items);
                    response.addAllUpdate(items);
                }

                send(messageSource, response, Result.Success);

                switch (oi.getChannel()) {
                    case SdkChannel.sdk_weixin: {
                        dealReportWeiXin(null, oi);
                        break;
                    }
                    case SdkChannel.sdk_shengye: {
                        dealReportShengYe(null, oi);
                        break;
                    }

                    default:
                        break;
                }

                if (oi.getChannel().equals(SdkChannel.sdk_weixin)) {
                    dealReport(null, oi);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            OrderInfo.unlockOrderInfo(pcode);
        }

    }

    private void send(MessageSource messageSource, PayMessage.GoodsOrderResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }

    private void dealReport(PayMessage.GoodsOrderResponse.Builder response, OrderInfo oi) {
        //江湖
//		参数名	必选	类型	说明
//		appID	是	string	平台分配的应用id
//		orderNo	是	string	平台订单号
//		amount	是	long	金额，分
//		sign	是	string	签名，sign = md5(appID + orderNo + amount + OPENKEY) ,openkey为平台分配参数

        String appID = SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_appid);
        String orderNo = oi.getMyorderid();
        String amount = String.valueOf(oi.getPayamount());

        String signstr = appID + orderNo + amount + SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_openkey);
        String sign = getMD5(signstr).toLowerCase();

        JSONObject postjson = new JSONObject();
        postjson.put("appID", appID);
        postjson.put("orderNo", orderNo);
        postjson.put("amount", amount);
        postjson.put("sign", sign);

        String ret = null;
        try {
            NameValuePair[] pair = PostUtil.getValuePair(postjson);
            ret = PostUtil.doPost(weixin_jh_finishorder_report, pair, 30000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("dealReport ret:" + ret);
    }

    private void dealReportWeiXin(PayMessage.GoodsOrderResponse.Builder response, OrderInfo oi) {
        String appID = SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_appid);
        String openkey = SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_openkey);
        dealReport(response, oi, appID, openkey);
    }

    private void dealReportShengYe(PayMessage.GoodsOrderResponse.Builder response, OrderInfo oi) {
        String appID = SDKParm.getSdkparmvalue(SdkParmEnum.shengye_jh_appid);
        String openkey = SDKParm.getSdkparmvalue(SdkParmEnum.shengye_jh_openkey);
        dealReport(response, oi, appID, openkey);
    }

    /**
     * 江湖上报订单完成
     *
     * @param response
     * @param oi
     * @param appID
     * @param openkey
     */
    private void dealReport(PayMessage.GoodsOrderResponse.Builder response, OrderInfo oi, String appID, String openkey) {
        //江湖
//		参数名	必选	类型	说明
//		appID	是	string	平台分配的应用id
//		orderNo	是	string	平台订单号
//		amount	是	long	金额，分
//		sign	是	string	签名，sign = md5(appID + orderNo + amount + OPENKEY) ,openkey为平台分配参数

//		String appID = SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_appid);
//		String openkey = SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_openkey);

        String orderNo = oi.getMyorderid();
        String amount = String.valueOf(oi.getPayamount());

        String signstr = appID + orderNo + amount + openkey;
        String sign = getMD5(signstr).toLowerCase();

        JSONObject postjson = new JSONObject();
        postjson.put("appID", appID);
        postjson.put("orderNo", orderNo);
        postjson.put("amount", amount);
        postjson.put("sign", sign);

        String ret = null;
        try {
            NameValuePair[] pair = PostUtil.getValuePair(postjson);
            ret = PostUtil.doPost(weixin_jh_finishorder_report, pair, 30000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("dealReport ret:" + ret);
    }

    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 进行utf-8编码
            byte[] bs = str.getBytes("utf-8");
            // 计算md5函数
            md.update(bs);
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            // return new BigInteger(1, md.digest()).toString(16);
            byte[] md5sum = md.digest();
            return toHex(md5sum);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String toHex(byte[] data) {
        char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        char[] chars = new char[data.length * 2];
        for (int i = 0; i < data.length; i++) {
            chars[i * 2] = HEX_DIGITS[(data[i] >> 4) & 0xf];
            chars[i * 2 + 1] = HEX_DIGITS[data[i] & 0xf];
        }
        return new String(chars);
    }
}
